package com.ycsj.goldmedalnewconcept.activity;

import java.io.File;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
//import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.bean.UpdateInfo;
import com.ycsj.goldmedalnewconcept.service.DownloadService;
import com.ycsj.goldmedalnewconcept.R;

public class SplashActivity extends Activity {

	private HttpUtils httpUtils;
	private static final int ANIMATION_DURATION = 2000;
	
	
	ImageView imageView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		ViewUtils.inject(this);
		playAnimation();
		
		httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.GET,
				"http://139.129.57.83:8080/Appandroid/updateinfo.xml", callBack);
		
		
		
	}
	@Override
	protected void onStop() {
		super.onStop();
		// 取消未执行的任务,注意，runnable对象必须是同一个
		handler.removeCallbacks(goNextUiRunnable);
	}
	private RequestCallBack<String> callBack = new RequestCallBack<String>() {
		private String xmlString;

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
//			Log.d("onSuccess", "onSuccess");

			xmlString = responseInfo.result;
//			Log.d("onSuccess", "splash"+xmlString);
			final UpdateInfo updateInfo = parseXML2JavaBean(xmlString);
//			Toast.makeText(SplashActivity.this, "", 0).show();
//			Log.d("onSuccess", "splash"+updateInfo);
			if (getVersionName().equals(updateInfo.getVersionName())) {
				
				goNextUi();
			} else {
				Log.d("onSuccess", "dddd");
				AlertDialog.Builder builder = new AlertDialog.Builder(
						SplashActivity.this);
				// 设置对话框的标题
				builder.setTitle("版本更新提醒");
				// 设置对话框的显示的消息
				builder.setMessage(updateInfo.getDescription());
				// 设置左边的按扭
				builder.setPositiveButton("立刻更新", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
//						Log.d("onSuccess", "欣然接受");
//						// 下载app
//						File dir = null;
//						if (Environment.MEDIA_MOUNTED.equals(Environment
//								.getExternalStorageState())) {
//							// /mnt/sdcard
//							dir = Environment.getExternalStorageDirectory();
//						} else {
//							// /data/data/cn.itcast.wh14.httputilsdemo/files
//							dir = getFilesDir();
//						}
//						Utils.downLoad(
//								"http://139.129.57.83:8080/Appandroid/金牌君.apk",
//								dir, new OnDownListener() {
//
//									@Override
//									public void downloadSuccess(File f) {
//										
//										 install(f);
//										
//									}
//
//									@Override
//									public void Fail() {
//										// 主界面
//										goNextUi();
//									}
//								});
						dialog.dismiss();
						Intent intent = new Intent(SplashActivity.this,DownloadService.class);
						intent.putExtra("url", "http://139.129.57.83:8080/Appandroid/jinpaijun.apk");
						startService(intent);
					}
				});

				// 设置右边的按钮
				builder.setNegativeButton("暂不更新", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 主界面
						goNextUi();
						finish();
					}

					
				});

				builder.show();

			}

		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// TODO Auto-generated method stub
//			Log.d("onSuccess", "onFailure");
		}
	};
	
	
	private void playAnimation() {
		AnimationSet animationSet = new AnimationSet(true);
		// 缩放的动画
		ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		scaleAnimation.setDuration(ANIMATION_DURATION);
		// 透明度动画
		AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
		alphaAnimation.setDuration(ANIMATION_DURATION);

		// 把两个动画效果装到一起
		animationSet.addAnimation(scaleAnimation);
		animationSet.addAnimation(alphaAnimation);

		animationSet.setAnimationListener(animationListener);

		// 同时播放两种动画效果
		imageView.startAnimation(animationSet);
	}
	
	static Handler handler = new Handler();
	private AnimationListener animationListener = new AnimationListener() {

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

		// 当动画结束时，会调用此方法
		@Override
		public void onAnimationEnd(Animation animation) {
			// 过一会
			handler.postDelayed(goNextUiRunnable, 2000);
		}
	};

	Runnable goNextUiRunnable = new Runnable() {

		@Override
		public void run() {
			goNextUi();

		}
	};
	
	private void goNextUi() {

		
		Class<?> targetActivity = JpjMainActivity.class;
		Intent intent = new Intent(this, targetActivity);
		startActivity(intent);
		// 关闭当前界面
		finish();
	}
	
	
	
	
	
	protected UpdateInfo parseXML2JavaBean(String xmlString) {
		UpdateInfo updateInfo = null;
		try {
			// 创建解析器工厂对象
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			// 使用工石对象产生解析器对象
			XmlPullParser parser = factory.newPullParser();
			// 设置解析的源。要解析的内容
			parser.setInput(new StringReader(xmlString));
			// 获取事件类型
			int type = parser.getEventType();
			
			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
				case XmlPullParser.START_TAG:
					if ("updateinfo".equals(parser.getName())) {
						updateInfo = new UpdateInfo();
//						Log.e("onSuccess", "123");
					} else if ("versionName".equals(parser.getName())) {
						updateInfo.setVersionName(parser.nextText());
					} else if ("url".equals(parser.getName())) {
						updateInfo.setUrl(parser.nextText());
					} else if ("description".equals(parser.getName())) {
						updateInfo.setDescription(parser.nextText());
					}
					
					break;
				default:
					break;
				}
				// 推进
				type = parser.next();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return updateInfo;
	}

	/**
	 * 显示应用的版本号
	 */
	private String getVersionName() {
		// PackageManager
		PackageManager packageManager = getPackageManager();
		// PackageInfo
		String versionName = null;
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			versionName = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionName;
	}

	public void install(File file) {

		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.addCategory(Intent.CATEGORY_DEFAULT);

		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		MobclickAgent.onResume(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		MobclickAgent.onPause(this);
	}
	
	

}
